const http = require('http');
const fs = require('fs');
const url = require('url');

const LISTEN_PORT = parseInt(process.argv[2]) || 8000;

const DEFAULT_PAGE = process.argv[3] || 'cros.html';

http.createServer((request, response) => {
        console.log(request.url);
        let page = fs.createReadStream(DEFAULT_PAGE);
        response.on('pipe', () => {
            console.log('0.pipe emits');
        });
        page.pipe(response);
        // page.pipe(response, { end: false });
        page.on('end', () => {
            console.log('1.page end emits');
            //if using pipe without pass option ({endd : false}), when all data is sent, src emits end event,the writeablestream will auto call end() method to flush data.
            //response.end('11111111');
        });
        response.on('finish', () => {
            console.log('3.finish emits');
        });
        response.on('unpipe', () => {
            console.log('2.unpipe emits');
        });
        response.on('close', () => {
            console.log('connection error happend: response close emits');
        });
    }).on('error', console.error)
    .listen(LISTEN_PORT);